// Copyright (c) 2011 Tim Niblett All Rights Reserved.
//
// File:        LoginServlet.java  (31-Oct-2011)
// Author:      tim

//
// Copyright in the whole and every part of this source file belongs to
// Tim Niblett (the Author) and may not be used,
// sold, licenced, transferred, copied or reproduced in whole or in
// part in any manner or form or in or on any media to any person
// other than in accordance with the terms of The Author's agreement
// or otherwise without the prior written consent of The Author.  All
// information contained in this source file is confidential information
// belonging to The Author and as such may not be disclosed other
// than in accordance with the terms of The Author's agreement, or
// otherwise, without the prior written consent of The Author.  As
// confidential information this source file must be kept fully and
// effectively secure at all times.
//


package com.quizh.login.web.user;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;

import com.quizh.login.core.test.TestBean;
import com.quizh.login.core.test.TestDao;
import com.quizh.login.dao.DaoFactory;
import com.quizh.login.web.BaseServlet;

@Path("ajaxLogin")
public class LoginServlet extends BaseServlet {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	static final Logger LOG = Logger.getLogger(LoginServlet.class.getName());

	public LoginServlet() {
		super(new DaoFactory());
	}
    LoginServlet(DaoFactory daoProvider) {
        super(daoProvider);
    }
    
    @GET
    public void doGet(@Context HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	TestBean bean = new TestBean();
    	bean.setId(1L);
    	bean.setValue("valor1");
    	TestDao dao = new TestDao();
    	bean = dao.put(bean);
    	dao.get(bean.getKey());
    	System.out.println(bean.toString());
//        showView(response, "login.ftl");
//    	response.sendRedirect("login.html");
    }

    private void test(long id , String  value) {
    	TestBean bean = new TestBean();
    	bean.setId(id);
    	bean.setValue(value);
    	TestDao dao = new TestDao();
    	bean = dao.put(bean);
    	dao.get(bean.getKey());
    	System.out.println(bean.toString());
    }
    @POST
    public String  doPost(@Context HttpServletRequest request, @FormParam(PASSWORD) String pass,
    		@FormParam(USERNAME) String name, @FormParam(REMEMBER_ME) String rem) throws ServletException, IOException {
    	this.test(Long.parseLong(name), rem);
        String response = null;
    	try {
            String password = StringUtils.clean(pass);
            String username =  StringUtils.clean(name);
            boolean rememberMe = LoginServlet.isTrue(rem);
            String host = request.getRemoteHost();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe, host);
            try {
                Subject subject = SecurityUtils.getSubject();
                loginWithNewSession(token, subject);
                //subject.login(token);
                response = issueJson(null, HTTP_STATUS_OK, MESSAGE, "ok");
            } catch (AuthenticationException e) {
            	response = issue(MIME_TEXT_PLAIN, HTTP_STATUS_NOT_FOUND, "cannot authorize " + username + ": " + e.getMessage(), null);
            }
        } catch (Exception e) {
        	response = issue(MIME_TEXT_PLAIN, HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal error: " + e.getMessage(), null);
        }
    	return response;
    }
    
    public static boolean isTrue(String param) {
        String value =  StringUtils.clean(param);
        return value != null &&
                (value.equalsIgnoreCase("true") ||
                        value.equalsIgnoreCase("t") ||
                        value.equalsIgnoreCase("1") ||
                        value.equalsIgnoreCase("enabled") ||
                        value.equalsIgnoreCase("y") ||
                        value.equalsIgnoreCase("yes") ||
                        value.equalsIgnoreCase("on"));
    }
}
